package com.eeGroup.config;

import com.eeGroup.constants.Const;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession(false); // 不自动创建新session

        // 排除的路径（如登录页、静态资源等）
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/login") ||
                requestURI.startsWith("/doLogin") ||
                requestURI.startsWith("/static/") ||
                requestURI.startsWith("/error")) {
            return true; // 放行
        }

        // 检查会话中是否存在用户标识

        if (session == null || session.getAttribute(Const.user) == null) {
            request.getSession().setAttribute(Const.msg, "请先登录！");
            response.sendRedirect("/login");
            return false; // 中断请求
        }

        return true; // 继续执行
    }
}
